package com.magic.item.service.impl;

import com.magic.item.mapper.CategoryMapper;
import com.magic.item.pojo.Category;
import com.magic.item.service.CategoryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lan.jianyuan
 * @create 2021-01-04-10:55
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    @Resource
    private CategoryMapper categoryMapper;
    
    /**
     * 根据parentId查询子类目
     * @param pid
     * @return
     */
    public List<Category> queryCategoryListByParentId(Long pid) {
        Category record = new Category();
        record.setParentId(pid);
        return this.categoryMapper.select(record);
    }
    
    /**
     * 添加商品分类
     * @param category
     * @return
     */
    @Transactional
    public void addCategory(Category category) {
        List<Category> categories = categoryMapper.selectCategoryByPid(category.getParentId());
        categories.forEach(category1 -> {
            if (!category1.getIsParent()) {
                categoryMapper.updateCategoryIsParent(category1.getId());
            }
        });
        this.categoryMapper.insertSelective(category);
    }
    
    /**
     * 修改商品分类
     * @param category
     */
    @Transactional
    public void updateCategory(Category category) {
        categoryMapper.updateCategoryName(category.getName(), category.getId());
    }
    
    /**
     * 删除商品分类
     * @param id
     */
    @Transactional
    public void deleteCategory(Long id) {
        List<Category> categories = categoryMapper.selectCategoryByPid(id);
        categoryMapper.deleteCategory(id);
        categories.forEach(category -> {
            List<Category> categories1 = categoryMapper.selectCategoryById(category.getParentId());
            if (CollectionUtils.isEmpty(categories1)) {
                categoryMapper.updateCategoryIsParents(category.getParentId());
            }
        });
    }
    /**
     * 根据分类id查分类信息
     * @param id
     * @return
     */
    @Override
    public List<Category> queryCategoryId(Long id) {
        return categoryMapper.selectCategoryByPid(id);
    }
    
    /**
     * 根据多个id查询分类名称
     * @param ids
     * @return
     */
    public List<String> queryNamesByIds(List<Long> ids) {
        List<Category> categories = this.categoryMapper.selectByIdList(ids);
        return categories.stream().map(category -> category.getName()).collect(Collectors.toList());
    }
}
